package trabajoISW2.data;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import trabajoISW2.domain.implementations.Book;

public class BookDAO extends BaseDAO implements IBookDAO {


	public BookDAO(){
		
	}

	@Override
	public List<Book> getBooks() {

		Query q = getEm().createQuery("Select b FROM Book b");
		return q.getResultList();

	}
	
	@Override
	public List<Book> getBookByTitle(String s){
		Query q = getEm().createQuery("Select b FROM Book b WHERE title LIKE '%"+s+"%'");
		List<Book> books = q.getResultList();
		return books;
		
	}
	

	@Override
	public Book getBook(String isbn) {

		return getEm().find(Book.class,isbn);

	}

	@Override
	public Book createBook(Book b) {
		getEm().getTransaction().begin();
		getEm().persist(b);
		getEm().getTransaction().commit();
		getEm().close();
		return b;

	}

	@Override
	public void updateBook(Book b) {
		getEm().getTransaction().begin();
		getEm().merge(b);
		getEm().getTransaction().commit();
		getEm().close();

	}

	@Override
	public void deleteBook(String isbn) {

		Book b = getEm().find(Book.class, isbn);
		if (b != null){
			
			getEm().getTransaction().begin();
			getEm().remove(b);
			getEm().getTransaction().commit();
			getEm().close();
		}
	}

}
